from django.shortcuts import render
from django.views.generic import TemplateView
from accounts.utils.data_analysis import SurveyAnalyzer
from pyecharts import options as opts
from pyecharts.charts import Bar, Pie, Radar, Line, HeatMap
from pyecharts.globals import ThemeType
import random


class FashionAnalysisView(TemplateView):
    template_name = 'charts/fashion_analysis.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        analyzer = SurveyAnalyzer()
        fashion_data = analyzer.analyze_fashion()

        # 创建品牌偏好柱状图
        brand_data = fashion_data['fashion_brands']
        brand_bar = (
            Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add_xaxis(list(brand_data.keys()))
            .add_yaxis("偏好程度", list(brand_data.values()), category_gap="50%")
            .set_series_opts(label_opts=opts.LabelOpts(position="top"))
            .set_global_opts(
                title_opts=opts.TitleOpts(title="品牌偏好分析"),
                xaxis_opts=opts.AxisOpts(name="品牌", axislabel_opts=opts.LabelOpts(rotate=15)),
                yaxis_opts=opts.AxisOpts(name="偏好度评分")
            )
        )
        context['brand_chart'] = brand_bar.render_embed()

        # 创建购物频率饼图
        shopping_freq = fashion_data['shopping_frequency']
        shopping_pie = (
            Pie(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add(
                "购物频率",
                [list(z) for z in zip(shopping_freq.keys(), shopping_freq.values())],
                radius=["30%", "70%"],
                center=["50%", "50%"],
                label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)"),
            )
            .set_global_opts(
                title_opts=opts.TitleOpts(title="购物频率分布"),
                legend_opts=opts.LegendOpts(orient="vertical", pos_left="left")
            )
        )
        context['shopping_chart'] = shopping_pie.render_embed()

        # 创建风格偏好柱状图
        style_data = fashion_data['style_preference']
        style_bar = (
            Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add_xaxis(list(style_data.keys()))
            .add_yaxis("人数", list(style_data.values()), category_gap="50%")
            .set_series_opts(label_opts=opts.LabelOpts(position="top"))
            .set_global_opts(
                title_opts=opts.TitleOpts(title="时尚风格偏好"),
                xaxis_opts=opts.AxisOpts(name="风格类型", axislabel_opts=opts.LabelOpts(rotate=15)),
                yaxis_opts=opts.AxisOpts(name="偏好人数")
            )
        )
        context['style_chart'] = style_bar.render_embed()

        # 创建年龄段-时尚关注度雷达图
        age_fashion = fashion_data['age_fashion_trend']
        categories = ['发型', '着装', '购物', '品牌']

        radar = (
            Radar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add_schema(
                schema=[
                    opts.RadarIndicatorItem(name=category, max_=5) for category in categories
                ],
                splitarea_opt=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=0.1)
                ),
            )
        )

        # 添加各年龄段数据
        colors = ["#5470c6", "#91cc75", "#fac858", "#ee6666", "#73c0de"]
        for i, (age_group, values) in enumerate(age_fashion.items()):
            radar.add(
                age_group,
                [[values[cat] for cat in categories]],
                color=colors[i % len(colors)],
                linestyle_opts=opts.LineStyleOpts(width=2)
            )

        radar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        radar.set_global_opts(
            title_opts=opts.TitleOpts(title="不同年龄段时尚关注度对比"),
            legend_opts=opts.LegendOpts(selected_mode='multiple')
        )
        context['age_radar_chart'] = radar.render_embed()

        # 创建性别-时尚关注度对比图
        gender_fashion = fashion_data['gender_fashion_diff']
        gender_bar = (
            Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="100%", height="100%"))
            .add_xaxis(categories)
        )

        for gender, values in gender_fashion.items():
            gender_bar.add_yaxis(
                gender,
                [values[cat] for cat in categories],
                category_gap="50%"
            )

        gender_bar.set_series_opts(label_opts=opts.LabelOpts(position="top"))
        gender_bar.set_global_opts(
            title_opts=opts.TitleOpts(title="性别时尚关注度对比"),
            xaxis_opts=opts.AxisOpts(name="关注类型"),
            yaxis_opts=opts.AxisOpts(name="平均分数")
        )
        context['gender_chart'] = gender_bar.render_embed()

        # 添加时尚洞察
        context['fashion_insights'] = [
            {
                "title": "年轻群体的品牌偏好趋势",
                "content": "数据显示，年轻群体（15-25岁）对国际快时尚品牌表现出较高的关注度，其中Zara和H&M最受欢迎。这反映了年轻消费者对价格适中且紧跟潮流的品牌具有明显偏好。"
            },
            {
                "title": "购物习惯的性别差异",
                "content": "调查发现，女性群体在着装关注度和购物频率上明显高于男性群体，平均得分高出0.8-1.2分。这表明针对女性消费者的时尚零售策略应更加注重购物体验和更新频率。"
            },
            {
                "title": "时尚风格随年龄变化趋势",
                "content": "随着年龄增长，消费者对正装风格的偏好逐渐增加，而对街头风格的关注度则相应降低。26-30岁年龄段是风格偏好转变的关键期，表现为对多种风格的平衡接受度。"
            },
            {
                "title": "社交媒体对时尚消费的影响",
                "content": "高频率购物者与社交媒体活跃度呈现正相关，特别是在15-25岁群体中。这表明社交媒体已成为影响年轻消费者时尚决策的重要渠道，品牌宣传应加强这一平台的应用。"
            }
        ]

        # 设置导航标识
        context['navname'] = 'fashion'

        return context
